/*
 * @Author: shijianxin
 * @Date: 2022-04-25 11:51:29
 * @Description: 图片上传组件
 */

import { PlusOutlined } from "@ant-design/icons";
import { message, Modal, Upload } from "antd";
import { UploadFile } from "antd/lib/upload/interface";
import React from "react";
import { IResponseData, IResponseError } from "../services/CommonType";

interface IImgUploaderProps {
  value?: string;
  onChange?: (imgUrl: string) => void;
}

interface IImgState {
  showModel: boolean;
}

export default class extends React.Component<IImgUploaderProps, IImgState> {
  state: IImgState = {
    showModel: false,
  };
  private getUploadContent() {
    if (!this.props.value) {
      return (
        <div>
          <PlusOutlined />
          <div style={{ marginTop: 8 }}>点击上传</div>
        </div>
      );
    } else {
      return null;
    }
  }
  private getFileList(): UploadFile[] {
    if (this.props.value) {
      return [
        {
          uid: this.props.value,
          name: this.props.value,
          url: "/api" + this.props.value,
        },
      ];
    }
    return [];
  }
  async handleRequest(p: any) {
    let formData = new FormData();
    formData.append(p.filename, p.file);
    const request = new Request(p.action, {
      method: "post",
      body: formData,
    });
    const resp: IResponseData<string> | IResponseError = await fetch(
      request
    ).then((resp) => resp.json());
    if (resp.err) {
      message.error("上传失败");
    } else {
      this.props.onChange && this.props.onChange(resp.data!);
    }
  }
  render() {
    return (
      <Upload
        action="/api/upload"
        name="imgfile"
        listType="picture-card"
        accept=".jpg,.png,.gif"
        fileList={this.getFileList()}
        customRequest={this.handleRequest.bind(this)}
        onRemove={() => {
          this.props.onChange && this.props.onChange("");
        }}
        onPreview={() => {
          this.setState({
            showModel: true,
          });
        }}
      >
        {this.getUploadContent()}
        <Modal
          visible={this.state.showModel}
          footer={null}
          onCancel={() => {
            this.setState({
              showModel: false,
            });
          }}
        >
          <img
            alt="example"
            style={{ width: "100%" }}
            src={"/api" + this.props.value}
          />
        </Modal>
      </Upload>
    );
  }
}
